package com.haoyun.mirage.auth.service.impl;

import com.haoyun.common.constant.SecurityConstants;
import com.haoyun.mirage.auth.client.UserServiceClient;
import com.haoyun.mirage.auth.security.UserDetail;
import com.haoyun.mirage.auth.service.IUserService;
import com.haoyun.mirage.auth.vo.RoleVO;
import com.haoyun.mirage.auth.vo.UserVO;
import com.xiaoleilu.hutool.collection.CollectionUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Created by twg on 2018/5/31.
 */
@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private UserServiceClient userServiceClient;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserVO user = userServiceClient.getUserRolesByName(username);
        if (CollectionUtil.isEmpty(user.getRolesSet()) || StrUtil.isBlank(user.getUserPassword())) {
            log.info("通过用户名：{}，获取用户密码、角色等信息为空！", username);
            throw new UsernameNotFoundException("用户不存在或者未分配角色！");
        }
        Set<RoleVO> roles = user.getRolesSet();
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(roles.size());
        for (RoleVO role : roles) {
            authorities.add(new SimpleGrantedAuthority(role.getRoleCode()));
        }
        return new UserDetail(user.getUserName(), user.getUserPassword(), user.isDisabled(), user.isNonExpired(),
                user.isPasswordNonExpired(), user.isNonLocked(), authorities, user.getId(),user.getCompId(),user.getRealName(),user.getUserLevel(),user.getSalt());
    }

    @Override
    public void saveCodeImage(String random, String code) {
        redisTemplate.opsForValue().set(String.format("%s:%s", SecurityConstants.DEFAULT_CODE_KEY, random), code, SecurityConstants.DEFAULT_IMAGE_EXPIRE, TimeUnit.SECONDS);
    }
}
